﻿<!DOCTYPE html>

<html lang="en">

<head>
    <meta charset="utf-8" />
    <title>colorConvert</title>
    <link rel="stylesheet" type="text/css" href="res/index.css" />

</head>

<body style="background:#cce8cc;">
    <div>
        float [0,1]:<input id="numInput" type="text" /><br/>
        <button onclick="onConvert()">convert</button>
        <button onclick="onReverse()">reverse</button>
        <br/> rbg: <span id="outRbg"></span>
        <br/> hex: <span id="outHex"></span>
        <div id="outColor" style="background:#33334d;width:300px;height:100px;"></div>
    </div>

    <script>
        function onConvert() {
            output(convert);
        }
        function convert(num) {
            var dec = Math.round(num * 255);
            var hex = dec.toString(16);
            return [dec, hex];
        }

        function onReverse() {
            output(reverse);
        }
        function reverse(num) {
            var dec = (num / 255).toFixed(2);
            var hex = Number(num).toString(16);
            return [dec, hex];
        }

        function output(cbFunc) {
            var sInput = document.getElementById('numInput').value;
            if (!sInput) {
                return;
            }
            var inputs = sInput.split(',');
            var sRgb = '', sHex = '';
            for (var i = 0; i < inputs.length; ++i) {
                var arr = cbFunc(inputs[i]);
                var dec = arr[0];
                var hex = arr[1];
                if (hex.length == 1) {
                    hex = '0' + hex;
                }
                sRgb += dec + ',';
                sHex += hex;
            }
            sRgb = sRgb.substr(0, sRgb.length - 1);
            document.getElementById('outRbg').innerText = sRgb;
            document.getElementById('outHex').innerText = sHex;
            document.getElementById('outColor').style.background = "#" + sHex;
            // console.log('onconvert:', sRgb);
        }
    </script>
</body>

</html>